package renmopr.tourguide.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;

/**
 * 检查是否登陆，也就是openid是否存在
 * 
 * @author opunc
 *
 */
public class LoginedInterceptor implements Interceptor {
	private static final Logger logger = LoggerFactory.getLogger(LoginedInterceptor.class);

	@Override
	public void intercept(Invocation inv) {
		boolean isDev = PropKit.getBoolean("devMode");
		Controller controller = inv.getController();
		HttpSession session = controller.getRequest().getSession(false);
		if (!isDev) {
			if (session != null) {
				if (TextUtil.isEmpty(controller.getSessionAttr(Consts.OPENID))) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("code", -1);
					map.put("message", "OPENID IS NOT EXISTED");
					inv.getController().renderJson(JsonKit.toJson(map));
					logger.info("openid is not existed.");
					return;
				}
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", -1);
				map.put("message", "SESSION IS NULL");
				inv.getController().renderJson(JsonKit.toJson(map));
				logger.info("session is null");
				return;
			}
		}
		inv.invoke();
	}
}
